/**
 * Copyright 2006 Brad Reynolds
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.leeloo.databinding.internal.ui;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;

/**
 * Utility for dealing with {@link IResource resources}.
 * 
 * @author Brad Reynolds
 */
public class Resources {
    private static final boolean DEBUG = DataBindingUIPlugin.getDefault().isDebugging()
            && "true".equalsIgnoreCase(Platform.getDebugOption("org.leeloo.databinding.ui/debug")); //$NON-NLS-1$//$NON-NLS-2$

    /**
     * @param className
     * @return resource
     */
    public static IResource getResourceForClassName(String className) {
        

        SearchPattern pattern = SearchPattern.createPattern(className,
                IJavaSearchConstants.CLASS,
                IJavaSearchConstants.DECLARATIONS,
                SearchPattern.R_EXACT_MATCH);
        IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
        ClassRequestor requestor = new ClassRequestor();

        SearchEngine engine = new SearchEngine();
        try {
            engine.search(pattern,
                    new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                    scope,
                    requestor,
                    null);
        } catch (CoreException exception) {
            exception.printStackTrace();
        }
        
        if (requestor.resource == null) {
            if (DEBUG) {
                System.out.println("Unable to load resource for [" + className + "].  Breakpoint could not be created."); //$NON-NLS-1$//$NON-NLS-2$
            }
        }

        return (requestor.resource != null) ? requestor.resource : null;
    }

    private static class ClassRequestor extends SearchRequestor {
        private IResource resource;

        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            if (resource == null) {
                this.resource = match.getResource();
            }
        }
    }
}